import axios from 'axios'

// Full config:  https://github.com/axios/axios#request-config
// axios.defaults.baseURL = process.env.baseURL || '';
// axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
const config = {
  // baseURL: process.env.baseURL || ' '
  baseURL: 'http://localhost:9527',
  // timeout: 60 * 1000, // Timeout
  withCredentials: true // Check cross-site Access-Control
}
const _axios = axios.create(config)
_axios.interceptors.request.use(
  function (config) {
    config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
    config.headers.Accept = '*/*'
    const token = localStorage.getItem('token')
    if (token != null) {
      // 把token添加到请求头上去
      config.headers.Authorization = token
    }
    if (token == null) {
      config.auth = {
        username: 'admin',
        password: '112233'
      }
    }
    // Do something before request is sent
    return config
  },
  function (error) {
    // Do something with request error
    return Promise.reject(error)
  }
)

// Add a response interceptor
_axios.interceptors.response.use(
  function (response) {
    // 200为成功
    if (response.status === 200) {
      // 存储token
      localStorage.setItem('token', response.data.access_token)
    }
    return response
  },
  function (error) {
    // Do something with response error
    console.log('=======>' + error)
    return Promise.reject(error)
  }
)

export default _axios
